﻿// <copyright file="TIIncludeDirectoriesParser.cs" company="Horiba Medical">
//     Copyright (c) Horiba Medical. All rights reserved.
// </copyright>
// <summary>
//     Provides an include directories parser for TI project files.
// </summary>

namespace DoxyOutParser.CodeCheck
{
	using System;
	using System.Collections.Generic;
	using System.IO;
	using System.Linq;
	using System.Text;

	/// <summary>
	/// Parses a TI project file to find the include directories specified within it.
	/// </summary>
	public class TIIncludeDirectoriesParser : IIncludeDirectoriesParser
	{
		/// <summary>
		/// The file which needs parsing.
		/// </summary>
		private string tiProjectFile;

		/// <summary>
		/// Initializes a new instance of the TIIncludeDirectoriesParser class.
		/// </summary>
		/// <param name="projectFile">The TI project file which needs parsing.</param>
		public TIIncludeDirectoriesParser(string projectFile)
		{
			// TODO Check the value of string and eventually check if exist or not.
			this.tiProjectFile = projectFile;
		}

		#region IIncludeDirsParser Members

		/// <summary>
		/// Returns a list of every include directories specified in a TI project file.
		/// </summary>
		/// <returns>The directory list.</returns>
		public string[] GetIncludeDirectoriesTable()
		{
			// Using of StreamReader to parse the file
			StreamReader tiProjectStreamReader = new StreamReader(this.tiProjectFile);
			string line = tiProjectStreamReader.ReadLine();

			List<string> includeDirsTempList = new List<string>();

			while (line != null)
			{
				if (line.Contains("-i\""))
				{
					line = line.Substring(line.IndexOf("-i\"", StringComparison.Ordinal));
					do
					{
						int startIndex = line.IndexOf("-i\"", StringComparison.Ordinal);

						int endIndex = line.IndexOf("\"", startIndex + 3, StringComparison.Ordinal);
						if (endIndex != -1 && endIndex > startIndex)
						{
							string includeDir = line.Substring(startIndex + 3, (endIndex - startIndex - 3));
							includeDirsTempList.Add(includeDir);
						}

						line = line.Substring(endIndex + 1);
					}
					while (line.Contains("-i\""));
					return includeDirsTempList.ToArray();
				}

				// Read Next Line
				line = tiProjectStreamReader.ReadLine();
			}

			return includeDirsTempList.ToArray();
		}

		#endregion
	}
}
